<template>
  <a-card class="general-card" title="规格列表" :bordered="false">
    <PickSearchColumn :columns="columnsSearch" @reset="(val) => {apiParams = {...apiParams, ...val}}" @search="(val) => {apiParams = {...apiParams, ...val}}">
    </PickSearchColumn>
    <a-row style="margin-bottom: 16px">
      <a-col :span="16">
        <a-space>
          <a-button type="primary"  @click="add">
            添加
          </a-button>
          <a-button @click="delAll">
            批量删除
          </a-button>
        </a-space>
      </a-col>
    </a-row>
    <PickTablePage ref="tablePageRef" :columns="columnsTable" :methods="sortMethods" :api="getSkuList"
      @delete="handleDelete" :checkbox="true" :bordered="true"  @selectTableChange="selectTableChange"
      @parentComponentData="parentComponentData" @editor="edit" :api-params="apiParams">
      <template #logo="{ data }">
        <a-image width="100" height="100" :src="data.logo" />
      </template>
    </PickTablePage>
  </a-card>
  <a-modal v-model:visible="modalVisible" :width="500">
    <template #title> {{ modalTitle }} </template>
    <a-form :model="form">
      <a-form-item field="specName" label="规格名称">
        <a-input v-model="form.specName" />
      </a-form-item>
      <a-form-item field="specValue" label="规格值">
        <a-select :style="{ width: '320px' }" placeholder="输入后回车添加" v-model="form.specValue" multiple allow-create>
          <a-option v-for="(item, itemIndex) in specValue" :key="itemIndex" :value="item">{{ item }}</a-option>
        </a-select>
      </a-form-item>
    </a-form>
    <template #footer>
      <div style="text-align: right">
        <a-button style="margin-right: 5px" @click="modalVisible = false">取消</a-button>
        <a-button type="primary"  @click="saveSpec">提交</a-button>
      </div>
    </template>
  </a-modal>
</template>

<script setup lang="ts">

import { PickSearchColumn, PickTablePage } from '@pickmall/ui-v3-components';
import { MethodsRule, ColumnsDataRule, SearchRule } from '@/types/global';
import { getSkuList, delSpec, insertSpec, updateSpec } from '@/api/goods';
import { ref, reactive, onMounted } from 'vue';
import useCurrentInstance from '@/hooks/useCurrentInstance';
import { Message } from '@arco-design/web-vue';

const apiParams = ref({});
const tablePageRef = ref<any>();
// 获取modal
const modal = useCurrentInstance().globalProperties?.$modal;
// 多选数据
const selectList = ref([]) // 接受子组件传过来的值
const modalTitle = ref<string>('') // 弹框标题
const ids = ref<string>(''); // 多选行id
const modalVisible = ref<boolean>(false) // 弹框是否显示
const modalType = ref<number>(0) // 编辑/添加
const dataList = ref([]) // 获取分页数据
const form = reactive({
  specName: "",
  specValue: [],
  id: ''
}) as any
const specValue = ref([])
const columnsSearch: Array<SearchRule> = [
  {
    label: '规格名称',
    model: 'specName',
    disabled: false,
    input: true,
  },
];

const columnsTable: ColumnsDataRule[] = [
  {
    title: '规格名称',
    dataIndex: 'specName',
    width: 150,
  },
  {
    title: '规格值',
    dataIndex: 'specValue',
    width: 150,
  },
];

const sortMethods: MethodsRule = {
  title: '操作',
  width: 250,
  fixed: 'right',
  methods: [
    {
      title: '编辑',
      callback: 'editor',
      type:"text" ,
      status:"warning"
    },
    {
      title: '删除',
      callback: 'delete',
      type:"text" ,
      status:"danger"
    },
  ],
};
// 父组件传过来的数据
const parentComponentData = (val: any) => {
  if (val) {
    dataList.value = val.records
  }
}
// 回调删除
function handleDelete(data: any) {
  modal.confirm({
    title: '确认删除',
    content: `您确认要删除${data.record.specName}?`,
    alignCenter: false,
    onOk: async () => {
      const res = await delSpec(data.record.id);
      if (res.data.success) {
        Message.success('删除成功');
        tablePageRef.value.init();
      }
    },
  });
}
// 添加
const add = () => {
  modalType.value = 0
  modalTitle.value = '添加'
  form.specName = ''
  form.specValue = []
  delete form.id
  specValue.value = []
  modalVisible.value = true
}
// 编辑
const edit = (v: any) => {
  console.log(v);
  modalType.value = 1
  modalTitle.value = '编辑'
  // 转换null为""
  for (let i = 0; i < v.record; i += 1) {
    if (v[i] === null) {
      v[i] = "";
    }
  }
  const localVal = v.record.specValue;
  form.specName = v.record.specName;

  form.id = v.record.id;
  form.specValue = v.record.specValue;
  if (localVal && localVal.indexOf(",") > 0) {
    form.specValue = localVal.split(',')
    specValue.value = form.specValue
  } else {
    specValue.value = []
  }
  modalVisible.value = true
}
// 选择的行
const selectTableChange = (val: any) => {
  selectList.value = val
}
// 批量删除
const delAll = () => {
  if (selectList.value.length <= 0) {
    Message.error('您还未选择要删除的数据');
    return;
  }
  selectList.value.forEach((item: any) => {
    ids.value += `${item.id},`;
  })
  const joinid = ids.value.substring(0, ids.value.length - 1);
  modal.confirm({
    title: '确认删除',
    content: `您确认要删除所选的${selectList.value.length}条数据?`,
    alignCenter: false,
    onOk: async () => {
      const res = await delSpec(joinid);
      if (res.data.success) {
        Message.success('删除成功');
        tablePageRef.value.init();
      }
    },
  });
}
// 提交
const saveSpec = () => {
  const params = {
    ...form,
    specValue: form.specValue.join(',')
  }
  if (modalType.value == 0) {
    if (dataList.value.find((item: any) => item.specName == form.specName)) {
      Message.error('请勿添加重复规格名称!');
      return;
    }
    delete params.id
    insertSpec(params).then((res: any) => {
      if (res.data.success) {
        Message.success('操作成功');
        modalVisible.value = false;
        tablePageRef.value.init();
      }
    })
  } else {
    updateSpec(form.id, params).then((res: any) => {
      if (res.data.success) {
        Message.success('操作成功');
        modalVisible.value = false;
        tablePageRef.value.init();
      }
    })
  }
}
</script>
